/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package models

import (
	"database/sql"
	"math/rand"
	"strconv"
	"time"

	"gitee.com/WisdomClassroom/core"
)

type User struct {
	AccountID            int32         `gorm:"primaryKey; type:integer; uniqueIndex:uk_user_accountID"`
	Name                 sql.NullString `gorm:"not null; type:varchar(32)"`
	Gender               sql.NullInt32  `gorm:"not null; type:integer; default:0"`
	Type                 sql.NullInt32  `gorm:"not null; type:integer"`
	IsManager            sql.NullBool   `gorm:"not null; type:bool; default:false"`
	PasswordSSHA         sql.NullString `gorm:"not null; type:char(64)"`
	PasswordSalt         sql.NullString `gorm:"not null; type:char(64)"`
	Classes              []ClassModel   `gorm:"many2many:class_student_bind; foreignKey:AccountID; joinForeignKey:StudentID; references:UUID; joinReferences:ClassUUID; constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
	WrongAnswerQuestions []Question     `gorm:"many2many:student_wrong_question_bind; foreignKey:AccountID; joinForeignKey:StudentID; references:UUID; joinReferences:QuestionUUID; constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
}

func (u *User) ComputePasswordSSHA(passwordMD5 string) string {
	return core.StringToSha256(passwordMD5 + u.PasswordSalt.String)
}

func (u *User) Check(passwordMD5 string) bool {
	return u.PasswordSSHA.String == u.ComputePasswordSSHA(passwordMD5)
}

func (u *User) SetPassword(PasswordMD5 string) {
	u.PasswordSalt = sql.NullString{String: u.GenSalt(), Valid: true}
	u.PasswordSSHA = sql.NullString{String: u.ComputePasswordSSHA(PasswordMD5), Valid: true}
}

func (u *User) GenSalt() string {
	return core.StringToSha256(time.Now().String() + strconv.Itoa(rand.Intn(102400)))
}
